<template>
  <div>
    <el-tree
      :data="treeList"
      :props="treeProps"
      node-key="id"
      show-checkbox
      default-expand-all
      :default-checked-keys="idList"
      @check-change="changeNode"
    ></el-tree>
  </div>
  <div class="flex">
    <el-button>清空</el-button>
    <el-button type="primary" @click="clickHandle">确定</el-button>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { treeListApi, roleListMenu, changeMenuApi } from "./api";
import { useRoute } from "vue-router";
const route = useRoute();

const treeProps = {
  // children属性是要告诉 tree 组件，在data里面哪个属性名是用来作用子级的
  children: "children",
  //   lable 是告诉 tree组件，在data里面哪个属性是用来显示文字的
  label: "title",
};

const treeList = ref<ItreeMenu[]>([]);

const idList = ref<number[]>([]);

Promise.all([
  treeListApi(),
  roleListMenu(parseInt(route.query.id as string)),
]).then((res) => {
  treeList.value = res[0].data;
  res[1].data.forEach((item) => {
    treeList.value.map((c) =>
      c.id === item.parentId ? idList.value.push(item.id) : idList.value.push()
    );
  });
});

const changeNode = (data: any, node: any, elem: any) => {
  if (node) {
    idList.value.push(data.id);
  } else {
    idList.value.forEach((item, index) => {
      if (item === data.id) {
        idList.value.splice(index, 1);
      }
    });
  }

  console.log("data:", data);
  console.log("node:", node);
  console.log("elem:", elem);
};

const clickHandle = () => {
  changeMenuApi({
    roleId: parseInt(route.query.id as string),
    // 把所有勾选的id发回服务器
    menuIds: idList.value,
  });
};
</script>

<style scoped lang="less">
.flex {
  padding: 20px;
  display: flex;
  justify-content: center;
}
</style>
